package com.itheima.homework;

import com.itheima.dao.TdUserMapper;
import com.itheima.bean.TdUser;
import com.itheima.utils.MybatisUtil;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/selectAll")
public class CheckedAllUser extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html; charset=UTF-8");
        //使用mybatis查询所有用户
        SqlSession session = MybatisUtil.getSession();
        TdUserMapper mapper = session.getMapper(TdUserMapper.class);
        List<TdUser> tdUsers = mapper.selectAll();
        //将查出来的信息写到网站上
        PrintWriter writer = resp.getWriter();
        writer.println("<!DOCTYPE html>\n" +
                "<html lang=\"en\">\n" +
                "<head>\n" +
                "    <meta charset=\"UTF-8\">\n" +
                "    <title>首页</title>\n" +
                "</head>\n" +
                "<body>\n" +
                "<a href=\"/selectAll\">查看所有用户</a>\n" +
                "\n" +
                "<table align=\"center\" width=\"300\" cellspacing=\"0\" border=\"1\">\n" +
                "    <tr>\n" +
                "        <th>id</th>\n" +
                "        <th>用户名</th>\n" +
                "        <th>密码</th>\n" +
                "    </tr>");
        //遍历写入网页
        for (TdUser tdUser : tdUsers) {
            String userName = tdUser.getUserName();
            Integer id = tdUser.getId();
            String passWord = tdUser.getPassWord();
            writer.println("<tr align=\"center\">\n" +
                    "        <td>" + id + "</td>\n" +
                    "        <td>" + userName + "</td>\n" +
                    "        <td>" + passWord + "</td>\n" +
                    "    </tr>");
        }
        writer.println("</table>\n" +
                "</body>\n" +
                "</html>");
        session.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}
